import { defineEventHandler, getHeader, readBody, createError } from "h3"
import { LemonSqueezyService } from "../../../services/lemonSqueezyService"

export default defineEventHandler(async (event) => {
  const signature = getHeader(event, "x-signature")
  const payload = await readBody(event)

  if (!signature) {
    throw createError({
      statusCode: 400,
      statusMessage: "Missing signature",
    })
  }

  try {
    await LemonSqueezyService.handleWebhook(payload, signature)
    return { success: true }
  } catch (error) {
    console.error("Webhook error:", error)
    throw createError({
      statusCode: 400,
      statusMessage: "Invalid webhook",
    })
  }
})
